import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useSettingsStore = defineStore('settings', () => {
  // 状态
  const configs = ref({})
  const loading = ref(false)
  
  // 获取配置列表
  const fetchConfigs = async (serviceType = 'flink') => {
    try {
      // ⚡ 优化：移除内部loading管理，由页面组件统一管理
      // loading.value = true
      const response = await api.get('/settings', {
        params: { service_type: serviceType }
      })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      // 合并配置而不是覆盖 - 后端直接在data下返回服务配置，不是data.configs
      const newConfigs = data || {}
      Object.keys(newConfigs).forEach(st => {
        configs.value[st] = newConfigs[st]
      })
      return response.data
    } catch (error) {
      storeLogger.error('获取配置列表失败:', error)
      ElMessage.error('获取配置列表失败')
      throw error
    }
    // finally {
    //   loading.value = false
    // }
  }
  
  // 保存配置
  const saveConfigs = async (environments) => {
    try {
      loading.value = true
      const response = await api.post('/settings', {
        environments: environments
      })
      ElMessage.success('配置保存成功')
      await fetchConfigs() // 刷新配置
      return response.data
    } catch (error) {
      storeLogger.error('保存配置失败:', error)
      ElMessage.error('保存配置失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 创建单个环境
  const createEnvironment = async (environmentData) => {
    try {
      loading.value = true
      const response = await api.post('/settings/environment', environmentData)
      ElMessage.success('环境创建成功')
      await fetchConfigs() // 刷新配置
      return response.data
    } catch (error) {
      storeLogger.error('创建环境失败:', error)
      ElMessage.error(error.response?.data?.error || '创建环境失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 更新单个环境
  const updateEnvironment = async (serviceType, name, environmentData) => {
    try {
      loading.value = true
      const response = await api.put(`/settings/environment/${encodeURIComponent(serviceType)}/${encodeURIComponent(name)}`, environmentData)
      ElMessage.success('服务配置更新成功')
      await fetchConfigs() // 刷新配置
      return response.data
    } catch (error) {
      storeLogger.error('更新服务配置失败:', error)
      ElMessage.error(error.response?.data?.error || '更新服务配置失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 删除单个环境
  const deleteEnvironment = async (serviceType, name) => {
    try {
      loading.value = true
      const response = await api.delete(`/settings/environment/${encodeURIComponent(serviceType)}/${encodeURIComponent(name)}`)
      ElMessage.success('服务配置删除成功')
      await fetchConfigs() // 刷新配置
      return response.data
    } catch (error) {
      storeLogger.error('删除服务配置失败:', error)
      ElMessage.error(error.response?.data?.error || '删除服务配置失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 批量删除环境
  const deleteEnvironments = async (configs) => {
    try {
      loading.value = true
      const deletePromises = configs.map(config => 
        api.delete(`/settings/environment/${encodeURIComponent(config.service_type)}/${encodeURIComponent(config.name)}`)
      )
      await Promise.all(deletePromises)
      ElMessage.success(`成功删除 ${configs.length} 个服务配置`)
      await fetchConfigs() // 刷新配置
      return true
    } catch (error) {
      storeLogger.error('批量删除服务配置失败:', error)
      ElMessage.error('批量删除服务配置失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 获取所有服务配置
  const getAllServiceConfigs = () => {
    const allConfigs = []
    Object.keys(configs.value).forEach(serviceType => {
      const serviceConfigs = configs.value[serviceType] || {}
      Object.keys(serviceConfigs).forEach(configName => {
        allConfigs.push({
          service_type: serviceType,
          name: configName,
          ...serviceConfigs[configName]
        })
      })
    })
    return allConfigs.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
  }
  
  // 获取指定服务类型的配置
  const getServiceConfigs = (serviceType) => {
    const serviceConfigs = configs.value[serviceType] || {}
    return Object.keys(serviceConfigs).map(name => ({
      service_type: serviceType,
      name,
      ...serviceConfigs[name]
    }))
  }
  
  // 获取Flink环境列表（保持向后兼容）
  const getFlinkEnvironments = () => {
    return getServiceConfigs('flink')
  }
  
  return {
    // 状态
    configs,
    loading,
    
    // 方法
    fetchConfigs,
    saveConfigs,
    createEnvironment,
    updateEnvironment,
    deleteEnvironment,
    deleteEnvironments,
    getAllServiceConfigs,
    getServiceConfigs,
    getFlinkEnvironments
  }
})
